<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 5/29/24
 * Time: 11:26 AM
 */

namespace App\Services;

use App\Models\WechatUserAdmin;
use Carbon\Carbon;
use App\Models\WechatAccount;
use App\Models\WechatAccountCustomer;

class StatisticsService
{
    public function getActiveUser($params)
    {
        $corpId = $params['corp_id'] ?? '';
    }


    /**
     * 获取用户排行榜
     *
     * @param $params
     * @return array
     */
    public function getUserRankings($params)
    {
        $corpId = $params['corp_id'] ?? '';
        $sort   = $params['sort'] ?? 'desc';

        $users = WechatAccount::query()
            ->with(['department' => function ($query) {
                $query->select('department_id', 'department_name');
            }])
            ->select('user_id', 'department_id', 'user_name')
            ->where('corp_id', $corpId)
            ->whereIn('user_id', UtilityService::getPermissionUserIds())
            ->get();

        $result = [];
        foreach ($users as $user) {
            $result[] = [
                'user_id'            => $user->user_id,
                'user_name'          => $user->user_name,
                'department_name'    => optional($user->department)->department_name ?? '',
                'customer_total_num' => WechatAccountCustomer::query()
                    ->where('corp_id', $corpId)
                    ->where('account_id', $user->user_id)
                    ->count(),
                'customer_today_num' => WechatAccountCustomer::query()
                    ->where('corp_id', $corpId)
                    ->where('account_id', $user->user_id)
                    ->where('add_time', Carbon::now()->toDateString())
                    ->count()
            ];
        }

        if ($sort == 'desc') {
            return collect($result)->sortByDesc('customer_total_num')->values()->all();
        } else {
            return collect($result)->sortBy('customer_total_num')->values()->all();
        }
    }



    public function getCustomerData($params)
    {
        $corpId = $params['corp_id'] ?? '';

    }
}
